package com.dk.mq;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerOrderly;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.dk.mapper.TabCollectMapper;
import com.dk.mapper.TabRouteMapper;
import com.dk.pojo.TabCollect;
import com.dk.pojo.TabRoute;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Component
public class MessageListener implements MessageListenerOrderly {
    @Autowired
    TabCollectMapper tabCollectMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TabRouteMapper tabRouteMapper;

    @Override
    public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
        Gson gson = new Gson();
        for (MessageExt msg : list) {
            try {
                String key = "RouteForSet:";
                String s = new String(msg.getBody(), "UTF-8");
                List<Integer> integerList = gson.fromJson(s,new TypeToken<List<Integer>>(){}.getType());
                int rid = integerList.get(0);
                int uid = integerList.get(1);
                System.out.println(rid+"成功！"+uid);
                TabCollect collect = new TabCollect();
                collect.setDate(new Date());
                collect.setRid(rid);
                collect.setUid(uid);
                tabCollectMapper.insertSelective(collect);
                System.out.println("存储成功");
                //同步redis收藏数据
                ZSetOperations opsForZSet = redisTemplate.opsForZSet();
                TabRoute tabRoute = tabRouteMapper.selectByPrimaryKey(rid);
                String route = gson.toJson(tabRoute);
                opsForZSet.incrementScore(key,route,1);
                System.out.println(s);

            } catch (Exception e) {
                if (msg.getReconsumeTimes()>3){
                    consumeOrderlyContext.setSuspendCurrentQueueTimeMillis(-1);
                    return ConsumeOrderlyStatus.SUCCESS;
                }
                e.printStackTrace();
                return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
            }
        }
        return ConsumeOrderlyStatus.SUCCESS;
    }
}
